import {
	createRouter,
	createWebHashHistory
} from "vue-router";
// createWebHistory 不带#
const index = () => import("@/views/index.vue");
// 登录页面
const login = () => import("@/views/login.vue");
// 商品了你报
const goods = () => import("@/views/goods/goods.vue");
const routes = [{
		path: "/login",
		name: "login",
		component: login,
	},
	{
		path: "/",
		component: index,
		meta:{
			requireAuth:true
		},
		children:[
			{
				path: "/goods",
				name: "商品列表",
				component: goods,
			}
		]
	},
];

const router = createRouter({
	history: createWebHashHistory(),
	routes
});

// 路由拦截器
router.beforeEach((to, from, next) => {
    // console.log(to.matched)
	if (to.matched.length != 0) {
        if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
            if (Boolean(localStorage.getItem("userInfo"))) { 
                next();
            } else {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
                })
            }
        } else {
            if (Boolean(localStorage.getItem("userInfo"))) { // 判断是否登录
                if (to.path != "/" && to.path != "/login") { //判断是否要跳到登录界面
                    next();
                } else {
                    /**
                     * 防刷新，如果登录，修改路由跳转到登录页面，修改路由为登录后的首页 
                     */
                    next({
                        path: '/index'
                    })
                }
            } else {
                next();
            }
        }
    } else {
        next({
            path: '/login',
            query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
        })
    }
})


export default router;
